package com.zqy.common.intercept;

import com.zqy.common.BusinessException;
import com.zqy.common.CommonErrorCode;
import com.zqy.common.ErrorCode;
import com.zqy.common.PmpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.UnexpectedRollbackException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

@ControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Value("${uapmicServer.dev:true}")
    protected boolean isDev;

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public PmpResult processException(HttpServletRequest request, HttpServletResponse response, Exception e) {
        if (e instanceof BusinessException) {
            // 捕获业务异常
            logger.info(e.getMessage(), e);
            BusinessException businessException = (BusinessException)e;
            ErrorCode errorCode = businessException.getErrorCode();
            return PmpResult.serviceError(errorCode.getDesc());
        } else if (e instanceof UnexpectedRollbackException) {
            logger.error(e.getMessage(), e);
            return PmpResult.serviceError("数据库连接异常");
        } else if (e instanceof SQLException) {
            logger.info(e.getMessage(), e);
            if (isDev) {
                return PmpResult.serviceError(e.getMessage());
            } else {
                return PmpResult.serviceError("SQL异常");
            }
        } else if (e instanceof RuntimeException) {
            logger.info(e.getMessage(), e);
            RuntimeException r1 = (RuntimeException)e;
            if (isDev) {
                return PmpResult.serviceError(r1.getMessage());
            } else {
                return PmpResult.serviceError("运行时异常");
            }
        } else {
            logger.error(e.getMessage(), e);
            return PmpResult.serviceError(CommonErrorCode.UNKNOWN.getDesc());
        }
    }
}
